package com.hmall.ebiz.utils;

import com.hmall.ebiz.model.DbConfig;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class AutoConnectDatabase {

    public static List<String> connectionDataBase(String driver, String url, String user, String password, String dbName) {
        //声明Connection对象
        Connection con;
        //驱动程序名
        //遍历查询结果集
        try {
            //加载驱动程序
            Class.forName(driver);
            //1.getConnection()方法，连接MySQL数据库！！
            con = DriverManager.getConnection(url,user,password);
            if(!con.isClosed())
                System.out.println("Succeeded connecting to the Database!");
            //要执行的SQL语句
            List<String> tableNames = new ArrayList<>();
            //2.创建statement类对象，用来执行SQL语句！！
            Statement statement = con.createStatement();
            //要执行的SQL语句
            System.out.println(dbName);
            ResultSet rs = statement.executeQuery("Show tables");;

            while(rs.next()) {
                tableNames.add(rs.getString(1));
            }
            rs.close();
            con.close();
            return tableNames;
        } catch(ClassNotFoundException e) {
            //数据库驱动类异常处理
            System.out.println("Sorry,can`t find the Driver!");
            e.printStackTrace();
        } catch(SQLException e) {
            //数据库连接失败异常处理
            e.printStackTrace();
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally{
            System.out.println("数据库数据成功获取！！");
        }
        return null;
    }

}
